<?php
/**
 * (logic) 同步星级&排名
 */
namespace App\Logic\Operation;

use App\Models\Basics\SysCountry;
use App\Models\Operation\BATotal;
use App\Models\Operation\Crawl\ReviewsFile;
use App\Util\RExcel;
use Illuminate\Support\Facades\DB;
class OperationTotalStar
{
    public static function handle($day)
    {
        $time = strtotime('-'.$day.' days');
        $date = date("Y-m-d",$time);
        $totalCount = BATotal::query()
            ->where('report_date',$date)
            ->count();
        if($totalCount == 0){
            return 0;
        }

        //国家
        $country = array_keys(CrawlReviews::$_baseUrl);
        foreach ($country as $_country){
            $countryId = SysCountry::getIdByCountry($_country);
            if(!$countryId)continue;

            //星级&排名
            $file = ReviewsFile::getFile($date,$countryId);
            if(!is_file($file))continue;
            $lines = RExcel::importCsvFile($file);
            DB::beginTransaction();
            try{
                foreach($lines as $k => $v){
                    if($k == 0)continue;
                    if(!is_array($v))continue;
                    $count = count($v);
                    if($count < 6)continue;
                    if($v[3] > 5)continue;
                    if(strlen($v[4]) > 60)continue;
                    if(strlen($v[5]) > 60)continue;

                    //运营总表
                    $total = BATotal::query()
                        ->where('report_date',$date)
                        ->where('country_id',$countryId)
                        ->where('classify_id',$v[0])
                        ->first();
                    if(!$total)continue;
                    if($count == 6){
                        $total->star = $v[3];
                        $total->b_rank = $v[4];
                        $total->s_rank = $v[5];
                    }else{
                        $total->star = $v[3];
                        $total->ratings = $v[4] ? trim($v[4]) : null;
                        $total->b_rank = $v[5];
                        $total->s_rank = $v[6];
                    }
                    $total->save();
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
        }
        return 1;
    }
}
